import api from '../utils/api'

// 订单服务
export const orderService = {
  // 创建订单
createOrder: async (orderData) => {
  console.log('创建订单请求参数:', orderData)
  try {
    const response = await api.post('/api/orders', orderData)
    console.log('创建订单响应:', response)
    return response
  } catch (error) {
    console.error('创建订单失败:', error)
    throw error
  }
},
  
  // 获取订单详情
  getOrderDetail: async (orderId) => {
    try {
      return await api.get(`/api/orders/${orderId}`)
    } catch (error) {
      throw error
    }
  },
  
  // 根据订单编号获取订单详情
  getOrderByOrderNo: async (orderNo) => {
    try {
      return await api.get(`/api/orders/order-no/${orderNo}`)
    } catch (error) {
      throw error
    }
  },
  
  // 获取用户订单列表（分页）- 无参数版本，用户ID由后端从认证信息获取
  getUserOrders: async (page = 0, size = 10) => {
    try {
      console.log('获取用户订单列表（认证用户）', '页码:', page, '大小:', size)
      const response = await api.get('/api/orders', {
        params: { page, size }
      })
      console.log('获取用户订单列表响应:', response)
      return response
    } catch (error) {
      console.error('获取用户订单列表失败:', error)
      throw error
    }
  },

  // 获取指定用户订单列表（分页）- 带userId参数版本
  getUserOrdersByUserId: async (userId, page = 1, size = 10) => {
    try {
      console.log('获取用户订单列表，用户ID:', userId)
      const response = await api.get(`/api/orders/user/${userId}`, {
        params: { page, size }
      })
      console.log('获取用户订单列表响应:', response)
      return response
    } catch (error) {
      console.error('获取用户订单列表失败:', error)
      throw error
    }
  },
  
  // 根据状态获取用户订单列表
  getUserOrdersByStatus: async (userId, status, page = 1, size = 10) => {
    try {
      return await api.get(`/api/orders/status/${status}`, {
        params: { page, size }
      })
    } catch (error) {
      throw error
    }
  },
  
  // 更新订单状态
  updateOrderStatus: async (orderId, status) => {
    try {
      return await api.put(`/api/orders/${orderId}/status`, { status })
    } catch (error) {
      throw error
    }
  },
  
  // 取消订单
  cancelOrder: async (orderId) => {
    try {
      return await api.put(`/api/orders/${orderId}/cancel`)
    } catch (error) {
      throw error
    }
  },
  
  // 删除订单
  deleteOrder: async (orderId) => {
    try {
      return await api.delete(`/api/orders/${orderId}`)
    } catch (error) {
      throw error
    }
  },
  
  // 支付订单
  payOrder: async (orderId, paymentMethod) => {
    try {
      console.log('支付订单请求参数:', { orderId, paymentMethod })
      return await api.post(`/api/orders/${orderId}/pay`, { paymentMethod })
    } catch (error) {
      console.error('支付订单失败:', error)
      throw error
    }
  }
}